package com.codechuan.hallo_web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_web.common.Constant;
import com.codechuan.hallo_web.entity.*;
import com.codechuan.hallo_web.mapper.*;
import com.codechuan.hallo_web.service.BlApiService;
import com.codechuan.hallo_web.thread.TxmEntity;
import com.codechuan.hallo_web.utils.EncryptionUtil;
import com.codechuan.hallo_web.utils.HttpUtil;
import com.codechuan.hallo_web.utils.RedisUtils;
import com.codechuan.hallo_web.utils.ResultUtils;
import lombok.Synchronized;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class BlApiServiceImpl implements BlApiService {

    @Resource
    private SysKeyMapper sysKeyMapper;
    @Resource
    private SysUserAccountMapper sysUserAccountMapper;
    @Resource
    private SysUserConfigMapper sysUserConfigMapper;
    @Resource
    private SysUserTokenMapper sysUserTokenMapper;
    @Resource
    private SysCityMapper sysCityMapper;
    @Resource
    private SysUserOrderMapper sysUserOrderMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysAppUpdateMapper sysAppUpdateMapper;


    /**
     * @param hashMap 数据 key account password type 0 登陆 1 充值
     * @return 返回成功或失败的数据
     * @Deprecated 百里登陆接口
     */
    @Override
    @Transactional
    public String login(HashMap<String, String> hashMap) {
        String account = hashMap.get("account");
        String password = hashMap.get("password");
        String key = hashMap.get("key");
        String type = hashMap.get("type");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 登陆逻辑
            if (type.equals("0")) {
                // 1.校验用户是不是存在和密码是不是正确
                ArrayList<SysUserAccount> sysUserAccounts = sysUserAccountMapper.selectListByAccount(account);
                if (sysUserAccounts.isEmpty()) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "账号不存在!", 500));
                }
                SysUserAccount sysUserAccount = sysUserAccounts.get(0);
                if (!sysUserAccount.getPassword().equals(password)) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "账号或密码错误!", 500));
                }
                // 2.校验用户是否被别人登陆
                String machineCode = hashMap.get("machineCode");
                if (sysUserAccount.getMachineCode() != null && !sysUserAccount.getMachineCode().equals(machineCode)) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "请先解绑!", 500));
                }


                // 4.校验是否到期
                if (sysUserAccount.getEndTime() == null) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "请您先充值~", 500));
                }
                if (sysUserAccount.getEndTime() != null) {
                    String sysTime = format.format(new Date());
                    LocalDateTime dateTimeA = LocalDateTime.parse(sysUserAccount.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    LocalDateTime dateTimeB = LocalDateTime.parse(sysTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    if (dateTimeA.isBefore(dateTimeB)) {
                        return EncryptionUtil.encrypt(ResultUtils.success(null, "卡密已到期~", 500));
                    }
                }

                // 5.获取软件版本号
                SysAppUpdate sysAppUpdate = sysAppUpdateMapper.selectByPrimaryKey("百里出行");

                // 6.todo 绑定机器码
                sysUserAccount.setMachineCode(machineCode);
                sysUserAccountMapper.updateByPrimaryKeySelective(sysUserAccount);


                Boolean b = stringRedisTemplate.opsForValue().getOperations().hasKey("LOGIN_BL_" + account);
                if (b == false) {
                    RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "LOGIN_BL_" + account);
                }
                return EncryptionUtil.encrypt(ResultUtils.success(sysAppUpdate.getVersion(), "登陆成功~", 200));
            }

            // 充值逻辑
            if (type.equals("1")) {
                // 1.校验用户是不是存在和密码是不是正确
                ArrayList<SysUserAccount> sysUserAccounts = sysUserAccountMapper.selectListByAccount(account);
                if (sysUserAccounts.isEmpty()) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "账号不存在!", 500));
                }

                SysUserAccount sysUserAccount = sysUserAccounts.get(0);
                if (!sysUserAccount.getPassword().equals(password)) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "账号或密码错误!", 500));
                }

                // 2.校验卡密是否存在
                SysKey sysKey = sysKeyMapper.selectByPrimaryKey(key);
                if (sysKey == null) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "卡密错误,或不存在!", 500));
                }

                // 3.校验卡密状态和是否已经激活
                if (sysKey.getStatus().equals("1")) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "卡密被封禁!", 500));
                }
                if (sysKey.getIsActivated().equals("1")) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "卡密已被激活,无法继续充值!", 500));
                }

                // 4.校验完成进行卡密充值
                Calendar calendar = Calendar.getInstance();
                // 定义修改结果 true为充值成功 false为充值失败
                boolean flag = false;
                // 获取卡密开头
                switch (sysKey.getKeyTypes()) {
                    case "0":
                        // 获取到期时间
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                        // 修改卡密和用户表信息
                        flag = updateAccountAndKey(sysUserAccount, sysKey, calendar, account);
                        break;
                    case "1":
                        calendar.add(Calendar.DAY_OF_MONTH, 7);
                        // 修改卡密和用户表信息
                        flag = updateAccountAndKey(sysUserAccount, sysKey, calendar, account);
                        break;
                    case "2":
                        calendar.add(Calendar.DAY_OF_MONTH, 30);
                        // 修改卡密和用户表信息
                        flag = updateAccountAndKey(sysUserAccount, sysKey, calendar, account);
                        break;
                    case "3":
                        // 在当前时间基础上，增加5小时
                        calendar.add(Calendar.HOUR_OF_DAY, 5);
                        // 修改卡密和用户表信息
                        flag = updateAccountAndKey(sysUserAccount, sysKey, calendar, account);
                        break;
                }
                if (flag) {
                    return EncryptionUtil.encrypt(ResultUtils.success(null, "会员充值成功,请登陆!", 200));
                }
                return EncryptionUtil.encrypt(ResultUtils.success(null, "会员充值失败!", 500));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @return 返回成功或者失败的消息
     * @Deprecated 注册用户
     */
    @Override
    public String registerUser(HashMap<String, String> hashMap) {
        String account = hashMap.get("account");
        String password = hashMap.get("password");
        try {
            // 1.校验用户名是否存在
            SysUserAccount queryOne = sysUserAccountMapper.selectByPrimaryKey(account);
            if (queryOne != null) {
                return EncryptionUtil.encrypt(ResultUtils.success(null, "用户名已存在!", 500));
            }
            // 2.注册用户
            SysUserAccount sysUserAccount = new SysUserAccount();
            sysUserAccount.setAccount(account);
            sysUserAccount.setPassword(password);
            sysUserAccount.setUnbindingNumber(0L);
            int insert = sysUserAccountMapper.insert(sysUserAccount);
            String result = "1";
            if (insert <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @return 返回用户配置文件
     * @Deprecated 读取用户配置
     */
    @Override
    public String selectUserConfig(HashMap<String, String> hashMap) {
        ArrayList<SysUserConfig> sysUserConfig = sysUserConfigMapper.selectList(hashMap.get("account"));
        if (!sysUserConfig.isEmpty()) {
            try {
                return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(sysUserConfig.get(0)), "success", 200));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                return EncryptionUtil.encrypt(ResultUtils.success("null", "success", 200));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            return EncryptionUtil.encrypt(ResultUtils.success("null", "success", 200));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 参数
     * @return 返回token集合
     * @Deprecated 读取用户token列表
     */
    @Override
    public String getUserTokenList(HashMap<String, String> hashMap) {
        ArrayList<SysUserToken> sysUserTokens = sysUserTokenMapper.selectToeknList(hashMap.get("account"));
        try {
            HashMap<String, String> hashMap1 = new HashMap<>();
            hashMap1.put("tokenList", JSONObject.toJSONString(sysUserTokens));
            return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(hashMap1), "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @return 返回城市编码
     * @Deprecated 获取排除城市编码
     */
    @Override
    public String selectPcCsCityCode(HashMap<String, String> hashMap) {
        StringBuilder stringBuilder = new StringBuilder();
        String cityName = hashMap.get("cityName");
        if (cityName.contains(",")) {
            String[] split = cityName.split(",");
            for (String s : split) {
                String cityCode = sysCityMapper.selectCodeByCityName(s);
                stringBuilder.append(cityCode).append(",");
            }
        } else {
            String cityCode = sysCityMapper.selectCodeByCityName(cityName);
            stringBuilder.append(cityCode).append(",");
        }
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(stringBuilder.toString(), "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 保存配置文件
     */
    @Transactional
    @Override
    public String saveUserConfig(HashMap<String, String> hashMap) {
        String data = hashMap.get("data");
        JSONObject jsonObject = JSONObject.parseObject(data);
        SysUserConfig sysUserConfig = new SysUserConfig();
        sysUserConfig.setAccount(jsonObject.getString("account"));
        sysUserConfig.setJdMs(jsonObject.getString("jdMs"));
        sysUserConfig.setRzMs(jsonObject.getString("rsMs"));
        sysUserConfig.setIsDw(jsonObject.getString("isDw"));

        sysUserConfig.setMinMoney(jsonObject.getString("minMoney"));
        sysUserConfig.setMaxMoney(jsonObject.getString("maxMoney"));
        sysUserConfig.setGlqSelect(jsonObject.getString("glqSelect"));

        sysUserConfig.setMinStart(jsonObject.getString("min_start"));
        sysUserConfig.setPxGz(jsonObject.getString("px_gz"));

        sysUserConfig.setPcCheck(jsonObject.getString("pc_check"));
        sysUserConfig.setMinPcNumber(jsonObject.getString("min_pc_number"));
        sysUserConfig.setMaxPcNumber(jsonObject.getString("max_pc_number"));

        sysUserConfig.setDxCheck(jsonObject.getString("dx_check"));
        sysUserConfig.setMinDxNumber(jsonObject.getString("min_dx_number"));
        sysUserConfig.setMaxDxNumber(jsonObject.getString("max_dx_number"));

        sysUserConfig.setSsCheck(jsonObject.getString("ss_check"));
        sysUserConfig.setMinSsNumber(jsonObject.getString("min_ss_number"));
        sysUserConfig.setMaxSsNumber(jsonObject.getString("max_ss_number"));

        sysUserConfig.setDjCheck(jsonObject.getString("dj_check"));
        sysUserConfig.setMinDjMoney(jsonObject.getString("min_dj_money"));
        // 先删除
        sysUserConfigMapper.deleteByPrimaryKey(jsonObject.getString("account"));

        sysUserConfigMapper.insertSelective(sysUserConfig);
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(null, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 新增一条用户token
     */
    @Override
    @Transactional
    public String insertUserToken(HashMap<String, String> hashMap) {
        String token = hashMap.get("token");
        String ticket = hashMap.get("ticket");
        String desc = hashMap.get("desc");
        String status = hashMap.get("status");
        String errorNumber = hashMap.get("errorNumber");
        String type = hashMap.get("type");
        String account = hashMap.get("account");
        SysUserToken sysUserToken = new SysUserToken();
        sysUserToken.setToken(token);
        sysUserToken.setAccount(account);
        sysUserToken.setTicket(ticket);
        sysUserToken.setDesc(desc);
        sysUserToken.setStatus(status);
        sysUserToken.setErrornumber(Integer.valueOf(errorNumber));
        sysUserToken.setType(type);
        // 如果是主号需要先删除
        if (sysUserToken.getType().equals("0")) {
            sysUserTokenMapper.deleteByPrimaryKey(sysUserToken.getAccount());
        }
        int insert = sysUserTokenMapper.insertSelective(sysUserToken);
        String result = "1";
        if (insert <= 0) {
            result = "0";
        }
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(String.valueOf(insert), "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 修改token状态
     */
    @Override
    public String updateUserTokenStatus(HashMap<String, String> hashMap) {
        String token = hashMap.get("token");
        String status = hashMap.get("status");
        try {
            int insert = sysUserTokenMapper.updateUserTokenStatus(token, status);
            String result = "1";
            if (insert <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 删除小号token
     */
    @Override
    public String deleteUserMinToken(HashMap<String, String> hashMap) {
        String token = hashMap.get("token");
        String account = hashMap.get("account");
        try {
            int insert = sysUserTokenMapper.deleteUserMinToken(token, account);
            String result = "1";
            if (insert <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 获取订单列表
     */
    @Override
    public String getUserOrderList(HashMap<String, String> hashMap) {
        String account = hashMap.get("account");
        String type = hashMap.get("type");
        try {
            List<SysUserOrder> sysUserOrders = sysUserOrderMapper.selectAllListByAccount(account, type);
            HashMap<String, String> data = new HashMap<>();
            data.put("orderList", JSONObject.toJSONString(sysUserOrders));
            return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(data), "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(null, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 新增用户订单
     */
    @Override
    public String addUserOrder(HashMap<String, String> hashMap) {
        SysUserOrder sysUserOrder = new SysUserOrder();
        sysUserOrder.setCreatetime(new Date());
        sysUserOrder.setDriverjourneyguid(hashMap.get("driverjourneyguid"));
        sysUserOrder.setPaxjourneyguid(hashMap.get("paxJourneyGuid"));
        sysUserOrder.setPrice(hashMap.get("price"));
        sysUserOrder.setPersonnumber(hashMap.get("personNumber"));
        sysUserOrder.setOrderdes(hashMap.get("orderDes"));
        sysUserOrder.setCarpooltext(hashMap.get("carPoolText"));
        sysUserOrder.setAccount(hashMap.get("account"));
        sysUserOrder.setMsg(hashMap.get("msg"));
        sysUserOrder.setStartaddress(hashMap.get("startAddress"));
        sysUserOrder.setEndaddress(hashMap.get("endAddress"));
        sysUserOrder.setPassengername(hashMap.get("passengerName"));
        sysUserOrder.setOrdertype(hashMap.get("orderType"));
        sysUserOrder.setStartdes(hashMap.get("startDes"));
        sysUserOrderMapper.insertSelective(sysUserOrder);
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(null, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 删除指定订单信息
     */
    @Override
    public String deleteOrderInfo(HashMap<String, String> hashMap) {
        try {
            int insert = sysUserOrderMapper.deleteByPrimaryKey(hashMap.get("paxJourneyGuid"));
            String result = "1";
            if (insert <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 删除所有订单信息
     */
    @Override
    public String deleteAllOrderByAccount(HashMap<String, String> hashMap) {
        try {
            int insert = sysUserOrderMapper.deleteAllOrder(hashMap.get("account"));
            String result = "1";
            if (insert <= 0) {
                result = "0";
            }
            return EncryptionUtil.encrypt(ResultUtils.success(result, "success", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param hashMap 参数
     * @Deprecated 解绑账号
     */
    @Override
    public String noBind(HashMap<String, String> hashMap) {
        String account = hashMap.get("account");
        // 通过BL + 账号获取次数
        Boolean b = stringRedisTemplate.opsForValue().getOperations().hasKey("BL_" + account);
        if (b) {
            // 获取解绑次数
            String noBindNumber = stringRedisTemplate.opsForValue().get("BL_" + account);
            Integer i = Integer.valueOf(noBindNumber);
            if (i > 5) {
                try {
                    return EncryptionUtil.encrypt(ResultUtils.success("1", "本周解绑次数已满!", 500));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                try {
                    RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "BL_" + account);
                    // 解绑账号机器吗
                    sysUserAccountMapper.noBindAccount(account);
                    return EncryptionUtil.encrypt(ResultUtils.success("1", "解绑成功,请重新登陆~", 200));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            try {
                RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "BL_" + account);
                // 解绑账号机器吗
                sysUserAccountMapper.noBindAccount(account);
                return EncryptionUtil.encrypt(ResultUtils.success("1", "解绑成功,请重新登陆~", 200));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    @Synchronized
    public String fuck(HashMap<String, String> hashMap) throws Exception {
        Constant.executorService.execute(new Runnable() {
            @Override
            public void run() {
                if (Constant.NUMBER_BL >= Constant.IP_SERVER.length) {
                    Constant.NUMBER_BL = 0;
                }
                Constant.result.put("address",Constant.IP_SERVER[Constant.NUMBER_BL]);
                Constant.result.put("address2",Constant.IP_SERVER2[Constant.NUMBER_BL]);
                Constant.NUMBER_BL++;
            }
        });
        return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(Constant.result), "success", 200));
    }

    @Override
    public String getDemo(HashMap<String, String> hashMap) {
        String number = hashMap.get("number");
        String ipAddress = HttpUtil.getIpAddress(number);
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(ipAddress, "ok", 200));
        } catch (Exception e) {
            return null;
        }
    }


    @Override
    public String init(HashMap<String, String> hashMap) {
        String token = hashMap.get("tocken");
        String ticket = hashMap.get("ticket");
        String data = hashMap.get("data");
        HashMap<String, String> stringStringHashMap = HttpUtil.initSlider(data, token, ticket);
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(JSONObject.toJSONString(stringStringHashMap), "解绑成功,请重新登陆~", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String callBack(HashMap<String, String> hashMap) {
        try {
            return EncryptionUtil.encrypt(ResultUtils.success(HttpUtil.callBack(hashMap), "解绑成功,请重新登陆~", 200));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * @param sysUserAccount 用户实体类
     * @param sysKey         卡密实体类
     * @param calendar       时间
     * @param account        卡密表需要绑定的账号
     * @Deprecated 修改用户表和卡密表信息
     */
    private boolean updateAccountAndKey(SysUserAccount sysUserAccount, SysKey sysKey, Calendar calendar, String account) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 修改用户表
        sysUserAccount.setEndTime(format.format(calendar.getTime()));
        int i = sysUserAccountMapper.updateByPrimaryKeySelective(sysUserAccount);
        // 修改卡密表
        sysKey.setIsActivated("1");
        sysKey.setExpirationTime(calendar.getTime());
        sysKey.setActivationTime(new Date());
        sysKey.setAccount(account);
        int i1 = sysKeyMapper.updateByPrimaryKeySelective(sysKey);
        if (i > 0 && i1 > 0) {
            return true;
        }
        return false;
    }


}
